package com.kmzx.one.project.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kmzx.one.common.exceptions.ParameterNullException;
import com.kmzx.one.common.utils.StringUtils;
import com.kmzx.one.project.entity.Brand;
import com.kmzx.one.project.mapper.BrandMapper;
import com.kmzx.one.project.mapper.CustomerMapper;
import com.kmzx.one.project.mapper.ProductMapper;
import com.kmzx.one.project.mapper.UserRankMapper;
import com.kmzx.one.project.others.dso.ProdCatePriceDso;
import com.kmzx.one.project.others.dso.ProdJoinDiscount;
import com.kmzx.one.project.others.dto.BrandInfo;
import com.kmzx.one.project.others.dto.FastProdInfo;
import com.kmzx.one.project.others.dto.GreatBrand;
import com.kmzx.one.project.others.dto.GreatBrandMain;
import com.kmzx.one.project.others.dto.ProdOutInfo;
import com.kmzx.one.project.others.dto.StraightInfo;
import com.kmzx.one.project.others.dto.UserRankInfo;
import com.kmzx.one.project.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BrandServiceImpl implements BrandService {

    @Autowired
    BrandMapper brandMapper;


    @Autowired
    UserRankMapper userRankMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public List<GreatBrand> findGreatBrand(String userId) throws Exception {

        List<BrandInfo> brandList = brandMapper.selectAllBrand();

        if (brandList != null && brandList.size() > 0) {
            List<String> prodIdList = brandList.stream().map(bl -> bl.getProdId()).collect(Collectors.toList());

            List<ProdCatePriceDso> prodPriceList = brandMapper.selectProdGroupPriceList(prodIdList);


            List<FastProdInfo> infos = productMapper.selectFastProdInfoPagedList(prodIdList);

            boolean fasts = false;
            if (infos != null && infos.size() > 0) {
                fasts = true;
            }
            if (prodPriceList != null && prodPriceList.size() > 0) {
                Map<String, Boolean> houseMap = new HashMap<>();
                Map<String, BigDecimal> priceMap = new HashMap<>();
                for (ProdCatePriceDso priceDso : prodPriceList) {
                    String productId = priceDso.getProductId();
                    priceMap.put(productId, priceDso.getMiniPrice());
                    houseMap.put(productId, priceDso.getNomNumbers() > 0);
                }
                Map<String, List<BrandInfo>> brandGroup = brandList.stream().collect(Collectors.groupingBy(BrandInfo::getBrandId));
                ArrayList<GreatBrand> brands = new ArrayList<>(brandGroup.size());

                Set<String> brandSet = brandGroup.keySet();

                for (String s : brandSet) {
                    GreatBrand greatBrand = new GreatBrand();
                    List<BrandInfo> brandInfos = brandGroup.get(s);

                    greatBrand.setBrandId(s).setBrandName(brandInfos.get(0).getBrandName());
                    greatBrand.setBrandPic(brandInfos.get(0).getBrandPic());

                    int length = brandInfos.size();
                    List<ProdOutInfo> prodList = new ArrayList<>(length);

                    for (BrandInfo brandInfo : brandInfos) {

                        ProdOutInfo prodOutInfo = new ProdOutInfo();
                        prodOutInfo.setProdName(brandInfo.getProdName()).setProdImg(brandInfo.getProdPic());
                        BigDecimal price = priceMap.get(brandInfo.getProdId());
                        if (price != null) {
                            prodOutInfo.setProdPrice(price);
                            // 活动价 ,要改
                            prodOutInfo.setCurrentPrice(price);
                        } else {
                            prodOutInfo.setProdPrice(BigDecimal.ZERO);
                            prodOutInfo.setCurrentPrice(BigDecimal.ZERO);
                        }
                        prodOutInfo.setProdId(brandInfo.getProdId());
                        Boolean aBoolean = houseMap.get(brandInfo.getProdId());
                        if (aBoolean != null) {
                            prodOutInfo.setHas(houseMap.get(brandInfo.getProdId()));
                        } else {
                            prodOutInfo.setHas(false);
                        }

                        if (fasts) {
                            prodOutInfo.setKinds(2);
                            for (FastProdInfo info : infos) {
                                if (brandInfo.getProdId().equals(info.getProdId())) {
                                    prodOutInfo.setCurrentPrice(info.getCurrentPrice());
                                    prodOutInfo.setFastIcon(info.getFastIcon());
                                }
                            }
                        }


                        prodList.add(prodOutInfo);
                    }
                    greatBrand.setProdList(prodList);
                    brands.add(greatBrand);
                }
                return brands;
            }
            return null;
        } else {
            return null;
        }
    }

    @Override
    public GreatBrandMain findBrandMainInfo(String brandId, String userId) throws Exception {

        Brand brand = brandMapper.selectById(brandId);
        List<String> list = brandMapper.selectBrandPics(brandId);
        GreatBrandMain main = new GreatBrandMain();
        main.setBrandId(brandId).setBrandName(brand.getCategoryName()).setCarouselsImg(list);
        main.setDescription(brand.getDescription());
        List<ProdOutInfo> infos = findProdByCateIdPager(brandId, userId, 1, 1000);
        main.setProdList(infos);
        return main;
    }


    public List<ProdOutInfo> findProdByCateIdPager(String brandId, String userId, Integer pageNum, Integer pageSize) throws Exception {

        pageNum = pageNum == null ? 1 : pageNum;
        pageSize = pageSize == null ? 10 : pageSize;

        if (StringUtils.isEmpty(brandId)) {
            throw new ParameterNullException("cateId为空");
        }

        PageHelper.startPage(pageNum, pageSize, true);
        Page<ProdOutInfo> result = productMapper.selectProdByCateIdPager(brandId);
        List<ProdOutInfo> end = result.getResult();
        if (end == null) {
            return Collections.emptyList();
        } else {

            List<String> prodIds = end.stream().map(qq -> qq.getProdId()).collect(Collectors.toList());
            List<ProdCatePriceDso> priceDsos = productMapper.selectProdGroupPriceList(prodIds);


            // 所有的商品打折活动,包括所有的商品
            List<ProdJoinDiscount> discounts = productMapper.selectAllProductJoinDiscount();

            boolean specific = false;
            List<String> specUsers = customerMapper.findSpecificUser();
            if (!CollectionUtils.isEmpty(specUsers) && (userId != null && userId != "")) {
                if (specUsers.contains(userId)) {
                    specific = true;
                }
            }
            if (!CollectionUtils.isEmpty(priceDsos)) {
                Map<String, List<ProdCatePriceDso>> map = priceDsos.stream().collect(Collectors.groupingBy(ProdCatePriceDso::getProductId));


                if (specific) {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniCost = prodCatePriceDsos.get(0).getMiniCost();
                            prod.setProdPrice(miniCost);
                            prod.setBeauty(miniCost);
                            prod.setCurrentPrice(miniCost);
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                        } else {
                            prod.setCurrentPrice(BigDecimal.ONE);
                            prod.setProdPrice(BigDecimal.ONE);
                            prod.setBeauty(BigDecimal.ONE);
                        }
                    }
                } else {
                    for (ProdOutInfo prod : end) {
                        List<ProdCatePriceDso> prodCatePriceDsos = map.get(prod.getProdId());
                        if (prodCatePriceDsos != null) {
                            BigDecimal miniPrice = prodCatePriceDsos.get(0).getMiniPrice();
                            prod.setHas(prodCatePriceDsos.get(0).getNomNumbers() > 0);
                            prod.setCurrentPrice(miniPrice);
                            prod.setProdPrice(miniPrice);
                            prod.setBeauty(miniPrice);
                        } else {
                            BigDecimal price = productMapper.selectProdGroupPrice(prod.getProdId());
                            if (price == null) {
                                prod.setCurrentPrice(BigDecimal.ONE);
                                prod.setProdPrice(BigDecimal.ONE);
                                prod.setBeauty(BigDecimal.ONE);
                            } else {
                                prod.setCurrentPrice(price);
                                prod.setBeauty(price);
                                prod.setProdPrice(price);
                            }
                        }
                    }
                    switchToFastProd(end, userId, discounts);
                }
            }
            return end;
        }
    }


    public List<ProdOutInfo> switchToFastProd(List<ProdOutInfo> end, String userId, List<ProdJoinDiscount> discounts) {
        //
        List<StraightInfo> infoList = productMapper.selectAllStraightInfo();
        if (infoList == null) {
            if (!CollectionUtils.isEmpty(discounts)) {
                Map<String, List<ProdJoinDiscount>> listMap = discounts.stream().collect(Collectors.groupingBy(ProdJoinDiscount::getProductId));

                for (ProdOutInfo prod : end) {
                    String prodId = prod.getProdId();
                    List<ProdJoinDiscount> joinDiscounts = listMap.get(prodId);
                    if (joinDiscounts != null) {
                        prod.setKinds(1);
                        Integer discountCate = joinDiscounts.get(0).getDiscountCate();
                        // 0折扣种类1固定金额种类
                        if (discountCate == 0) {
                            prod.setCurrentPrice(prod.getProdPrice().multiply(joinDiscounts.get(0).getDiscountNum()));
                        } else if (discountCate == 1) {
                            prod.setCurrentPrice(joinDiscounts.get(0).getDiscountNum());
                        }
                        prod.setBeauty(prod.getCurrentPrice());
                        prod.setDiscountImg(joinDiscounts.get(0).getDiscountImg());
                    }
                }
            }
            return end;
        }
        if (infoList != null && infoList.size() > 0) {
            UserRankInfo userRankInfo = userRankMapper.selectUserRankTabs(userId);
            boolean had = false;
            if (userRankInfo != null) {

                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    had = true;
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            } else {
                had = true;
                List<FastProdInfo> fastProdList = new ArrayList<>();
                for (StraightInfo info : infoList) {
                    String id = info.getId();
                    Page<FastProdInfo> infos = productMapper.selectFastProdInfoPaged(id);
                    fastProdList.addAll(infos.getResult());
                }
                if (had) {
                    for (ProdOutInfo prodOutInfo : end) {
                        for (FastProdInfo fastProdInfo : fastProdList) {
                            if (prodOutInfo.getProdId().equals(fastProdInfo.getProdId())) {
                                prodOutInfo.setFastIcon(fastProdInfo.getFastIcon());
                                prodOutInfo.setCurrentPrice(fastProdInfo.getCurrentPrice());
                                prodOutInfo.setBeauty(fastProdInfo.getBeauty());
                                prodOutInfo.setKinds(2);
                            }
                        }
                    }
                }
            }
        }
        return end;
    }
}
